package com.xdy.music.util;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class ImageUtils {
    public static BufferedImage toBufferedImage(Image image){
        if (image instanceof BufferedImage){
            return (BufferedImage) image;
        }
        image = new ImageIcon(image).getImage();
        boolean hasAlpha = false;
        BufferedImage bImage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        int transparency = Transparency.OPAQUE;
        if (hasAlpha){
            transparency = Transparency.BITMASK;
        }
        GraphicsDevice gs = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gs.getDefaultConfiguration();
        bImage = gc.createCompatibleImage(image.getWidth(null),image.getHeight(null),transparency);
        if (bImage == null){
            int type = BufferedImage.TYPE_INT_RGB;
            if (hasAlpha){
                type = BufferedImage.TYPE_INT_ARGB;
            }
            bImage = new BufferedImage(image.getWidth(null),image.getHeight(null),type);
        }
        Graphics g = bImage.createGraphics();
        g.drawImage(image,0,0,null);
        g.dispose();
        return bImage;
    }
}
